import Qfpage from '../../components/Qfpage/Qfpage';
import { Table,Button,Drawer,Space,Form,Input,InputNumber,message,Popconfirm,Typography,Col,Row,Pagination,Radio,Select,Cascader,Tag  } from 'antd';
import { useMemo,useEffect,useState,useLayoutEffect } from "react";
import { getAllRoom,addRoom,delRoom,editRoom } from "../../api/room"
import { getAllBuild } from '../../api/build';
import { getAllType } from "../../api/roomType";



const RoomList = ()=> {

    //获取全部的楼栋信息   start
    const [ build,setBuild] = useState([])
    const getBuild = async ()=>{
        let res = await getAllBuild({});
        console.log('获取楼栋信息res',res)

        //处理提取出楼栋楼层信息
        const temarr = res.data.map(item=>({
            label:item.name,
            value:item._id,
            children: item.floorInfo.map(it=>({ label:it,value:it }))
        }))
        setBuild(temarr)
    };

    useEffect(()=>{
        getBuild()
    },[])
    //获取全部的楼栋信息   end

    //获取全部的房型   start

    const [type, setType] = useState();
    const getTypes = async ()=>{
        const res = await getAllType({limit:1000});
        // console.log('查询到的房型信息', res.data.map(item=>({ label: item.name, value:item._id})))
        setType(res.data.map(item=>({ label: item.name, value:item._id})))
    }

    useEffect(()=>{
        getTypes();
    },[])

    //获取全部的房型   end

      



    const [data, setData] = useState([]);
    const [limit, setLinit] = useState(30);
    const [page, setPage] = useState(1);
    const [total ,setTotal] = useState(0); // 总数

    //获取表格数据
    // const [pagination, setPagination] = useState({
    //     current: 1,
    //     pageSize: 10,
    //   });

    const getData = async ()=>{
        const postData = { limit,page };
        if(name) postData.name = name;
        if(price) postData.price = price;
        console.log(postData)

        let res = await getAllRoom(postData);
        const { success,data,count } = res;
        if(success) {
            setData(data)
            setTotal(count)
        };
    };

    // 条件过滤
    const [name, setName] = useState('');
    const [price,setPrice] = useState('');

    useLayoutEffect(()=>{
        getData();//获取表格数据
    },[limit,page]);


    
    const columns = useMemo(()=>[
        {
          title: '房间名称',
          dataIndex: 'roomName',
          key: 'roomName',
        },
        {
            title: '楼层',
            dataIndex: 'floor',
            key: 'floor',
        },
        {
            title: '是否有窗',
            dataIndex: 'hasWindow',
            key: 'hasWindow',
            render: (record) => {
                console.log('这是这行的状态',record)
                // const { hasWindow } = record
                const color =  record ? '#87d068':'#f50'
                const txt =  record ? '有':'无'
                return <Tag color={color}> { txt } </Tag>
            }
        },
        {
            title: '靠近马路',
            dataIndex: 'isClose2Road',
            key: 'isClose2Road',
            render: (record) => {
                // const { hasWindow } = record
                const color =  record ? '#87d068':'#f50'
                const txt =  record ? '有':'否'
                return <Tag color={color}> { txt } </Tag>
            }
        },
        {
            title: '是否允许吸烟',
            dataIndex: 'isSmoke',
            key: 'isSmoke',
            render: (record) => {
                // const { hasWindow } = record
                const color =  record ? '#87d068':'#f50'
                const txt =  record ? '有':'否'
                return <Tag color={color}> { txt } </Tag>
            }
        },
    
    
        {
            title: '高温房',
            dataIndex: 'isHigh',
            key: 'isHigh',
            render: (record) => {
                // const { hasWindow } = record
                const color =  record ? '#87d068':'#f50'
                const txt =  record ? '有':'否'
                return <Tag color={color}> { txt } </Tag>
            }
        },
        {
            title: '操作',
            key: 'colKey',
            render: (record) => {
                return (
                    <>
                        <Button 
                            type="primary" 
                            size="small" 
                            style={{marginRight:"15px"}} 
                            onClick={() => {return handleRevise(record), showDrawers()}}
                        >
                            修改
                        </Button>

                        <Popconfirm 
                            title="你确定要删除吗?" 
                            okText="确认删除"
                            cancelText="再想想" 
                            onConfirm={() => handleDelete(record._id)}
                        >
                            <Button type="primary" size="small">删除</Button>
                        </Popconfirm>
                    </>
                );
            }
           
        },
      ],[]) 



      const hand = async (record) => {
        // form.setFieldsValue(record)
        // setCurRow(record)
        console.log(record)
        };


    //添加房间的操作  start
    const [form1] = Form.useForm();
    
    const [visible, setVisible] = useState(false);

    const showDrawer = () => {
        setVisible(true);
    };

    const onClose = () => {
        setVisible(false);
    };

    const onFinish = async (value) => {

        onClose()
        console.log('这是我添加的房间',value)
        const { bandf, ...postData } = value;
        const [ buildId, floor ] = bandf
        let res = await addRoom({
            ...postData,
            floor,
            buildId
        });
        const { success } = res;
        if(!success) return message.error('添加失败');
        message.success('添加成功');
        getData()//刷新表格
        form1.resetFields();//重置表单内容
    };

    const onFinishFailed = () => {
        console.log('Failed:', "errorInfo");
    };
    //添加房间的操作  end


    //删除房型的操作  start
    const handleDelete = async (id) => {
        console.log(id)
        let res = await delRoom({roomid: id});
        const { success } = res;
        if(!success) return message.error('删除失败');
        message.success('删除成功');
        getData()//刷新表格

        };
    //删除房型的操作   end


    //修改房间的操作   start
    const [form] = Form.useForm()

    const [visibles, setVisibles] = useState(false);

    const showDrawers = () => {
        setVisibles(true);
    };

    const onCloses = () => {
        setVisibles(false);
    };

    const [curRow,setCurRow] = useState(null)

    const handleRevise = async (record) => {
        // console.log(record)
        form.setFieldsValue({
            ...record,
            bandf:[record.buildId,record.floor]
        })
        setCurRow(record)
        };

    const onFinishs = async (type) => {

        onCloses()

        const values = type; // 得到所有的表单的值
        const { bandf,...postData } = values;
        const [buildId,floor] = bandf;
        let res = await editRoom({
            ...postData,
            roomid:curRow._id,
            buildId, 
            floor
        });
        const { success } = res;
        if(!success) return message.error('修改失败');
        message.success('修改成功');
        getData()//刷新表格
    };

    const onFinishFaileds = () => {
        console.log('Failed:', "errorInfo");
    };
    //修改房间的操作   end
        


    return (
        <Qfpage title='房间管理'>
            <Row gutter={10}>
                <Col span={6}>
                    <Button
                        type="primary" 
                        style={{margin:"15px"}} 
                        onClick={showDrawer}
                    >
                        添加房间
                    </Button>
                </Col>
                <Col span={4}>
                    <Input placeholder="输入你要查询的房间" style={{margin:"15px"}} onChange={(e)=>setName(e.target.value)}/> 
                </Col>
                <Col span={4}>
                    <Input placeholder="按价格查询"style={{margin:"15px"}} onChange={(e)=>setPrice(e.target.value)}/>
                </Col>
                <Col span={8}>
                    <Button type="primary" style={{margin:"15px"}} onClick={getData}>立即查询</Button>
                </Col>
            </Row>
            
            <Table 
                dataSource={data} 
                columns={columns} 
                rowKey="_id"
                // pagination={{
                //     showSizeChanger:"true",
                //     pageSize:6,
                //     pageSizeOptions:[10, 20, 50, 100],
                //     // pageSizeOptions: limit,
                //     // total,
                //     onChange(page, pageSize){
                //        setPage(current);
                //        setLimit(pageSize)
                 
                //     }
                //   }}
            />

            <Drawer 
                title="添加房型"
                placement="right" 
                onClose={onClose} 
                visible={visible} 
                size="large"
            >
    
                <Form
                    initialValues={
                        {
                            roomName: "",
                            bandf:"",
                            type:"",
                            phone4out:"",
                            phone4out:"",
                            direction:"a",
                            hasWindow:true,
                            isClose2Road:false,
                            isSmoke:false,
                            isNoise:false,
                            isHigh:false,

                        }
                    }
                    onFinish={onFinish}
                    onFinishFailed={onFinishFailed}
                    form={form1}

                >
                    <Form.Item label="房间名" name="roomName" rules={[{ required: true, message: '别急!!来把房间名填了先!!!' }]}>
                        <Input placeholder="请填写房间名称" />
                    </Form.Item>

                    <Form.Item label="所在楼栋楼层" name="bandf" rules={[{ required: true, message: '请选择楼栋楼层' }]}>
                        <Cascader options={build} placeholder="请选择楼栋楼层"/>
                    </Form.Item>

                    <Form.Item label="选择房型" name="type" rules={[{ required: true, message: '请选择房型' }]}>
                        <Select options={type} placeholder="请选择房型"></Select>
                    </Form.Item>

                    <Form.Item label="内线电话" name="phone4in" rules={[{ required: true, message: '请填写内线电话' }]}>
                        <Input placeholder="请填写内线电话" />
                    </Form.Item>
                    <Form.Item label="外线电话" name="phone4out" rules={[{ required: true, message: '请填写外线电话' }]}>
                        <Input placeholder="请填写外线电话" />
                    </Form.Item>

                    <Form.Item label="房间朝向" name="direction">
                        <Radio.Group defaultValue="a" buttonStyle="solid">
                            <Radio.Button value="a">东</Radio.Button>
                            <Radio.Button value="b">西</Radio.Button>
                            <Radio.Button value="c">南</Radio.Button>
                            <Radio.Button value="d">北</Radio.Button>
                        </Radio.Group>
                    </Form.Item>

                    <Form.Item label="是否有窗户" name="hasWindow">
                        <Radio.Group defaultValue={false} buttonStyle="solid">
                            <Radio.Button value={true}>是</Radio.Button>
                            <Radio.Button value={false}>否</Radio.Button>
                        </Radio.Group>
                    </Form.Item>

                    <Form.Item label="是否靠近马路" name="isClose2Road">
                        <Radio.Group defaultValue={false} buttonStyle="solid">
                            <Radio.Button value={true}>是</Radio.Button>
                            <Radio.Button value={false}>否</Radio.Button>
                        </Radio.Group>
                    </Form.Item>

                    <Form.Item label="是否允许吸烟" name="isSmoke">
                        <Radio.Group defaultValue={false} buttonStyle="solid">
                            <Radio.Button value={true}>是</Radio.Button>
                            <Radio.Button value={false}>否</Radio.Button>
                        </Radio.Group>
                    </Form.Item>

                    <Form.Item label="是否是噪音房" name="isNoise">
                        <Radio.Group defaultValue={false} buttonStyle="solid">
                            <Radio.Button value={true}>是</Radio.Button>
                            <Radio.Button value={false}>否</Radio.Button>
                        </Radio.Group>
                    </Form.Item>

                    <Form.Item label="是否是高温房" name="isHigh">
                        <Radio.Group defaultValue={false} buttonStyle="solid">
                            <Radio.Button value={true}>是</Radio.Button>
                            <Radio.Button value={false}>否</Radio.Button>
                        </Radio.Group>
                    </Form.Item>

                    <Button onClick={onClose}>取消</Button>
                    <Button type="primary" htmlType="submit">
                        立即添加
                    </Button>

                </Form>
            </Drawer>

            <Drawer 
                title="修改房型"
                placement="right" 
                onClose={onCloses} 
                visible={visibles} 
                size="large"
            >
    
                <Form
                    initialValues={
                        {
                            roomName: "",
                            bandf:"",
                            type:"",
                            phone4out:"",
                            phone4out:"",
                            direction:"a",
                            hasWindow:true,
                            isClose2Road:false,
                            isSmoke:false,
                            isNoise:false,
                            isHigh:false,

                        }
                    }
                    onFinish={onFinishs}
                    onFinishFailed={onFinishFaileds}
                    form={form}

                >
                    <Form.Item label="房间名" name="roomName" rules={[{ required: true, message: '别急!!来把房间名填了先!!!' }]}>
                        <Input placeholder="请填写房间名称" />
                    </Form.Item>

                    <Form.Item label="所在楼栋楼层" name="bandf" rules={[{ required: true, message: '请选择楼栋楼层' }]}>
                        <Cascader options={build} placeholder="请选择楼栋楼层"/>
                    </Form.Item>

                    <Form.Item label="选择房型" name="type" rules={[{ required: true, message: '请选择房型' }]}>
                        <Select options={type} placeholder="请选择房型"></Select>
                    </Form.Item>

                    <Form.Item label="内线电话" name="phone4in" rules={[{ required: true, message: '请填写内线电话' }]}>
                        <Input placeholder="请填写内线电话" />
                    </Form.Item>
                    <Form.Item label="外线电话" name="phone4out" rules={[{ required: true, message: '请填写外线电话' }]}>
                        <Input placeholder="请填写外线电话" />
                    </Form.Item>

                    <Form.Item label="房间朝向" name="direction">
                        <Radio.Group defaultValue="a" buttonStyle="solid">
                            <Radio.Button value="a">东</Radio.Button>
                            <Radio.Button value="b">西</Radio.Button>
                            <Radio.Button value="c">南</Radio.Button>
                            <Radio.Button value="d">北</Radio.Button>
                        </Radio.Group>
                    </Form.Item>

                    <Form.Item label="是否有窗户" name="hasWindow">
                        <Radio.Group defaultValue={false} buttonStyle="solid">
                            <Radio.Button value={true}>是</Radio.Button>
                            <Radio.Button value={false}>否</Radio.Button>
                        </Radio.Group>
                    </Form.Item>

                    <Form.Item label="是否靠近马路" name="isClose2Road">
                        <Radio.Group defaultValue={false} buttonStyle="solid">
                            <Radio.Button value={true}>是</Radio.Button>
                            <Radio.Button value={false}>否</Radio.Button>
                        </Radio.Group>
                    </Form.Item>

                    <Form.Item label="是否允许吸烟" name="isSmoke">
                        <Radio.Group defaultValue={false} buttonStyle="solid">
                            <Radio.Button value={true}>是</Radio.Button>
                            <Radio.Button value={false}>否</Radio.Button>
                        </Radio.Group>
                    </Form.Item>

                    <Form.Item label="是否是噪音房" name="isNoise">
                        <Radio.Group defaultValue={false} buttonStyle="solid">
                            <Radio.Button value={true}>是</Radio.Button>
                            <Radio.Button value={false}>否</Radio.Button>
                        </Radio.Group>
                    </Form.Item>

                    <Form.Item label="是否是高温房" name="isHigh">
                        <Radio.Group defaultValue={false} buttonStyle="solid">
                            <Radio.Button value={true}>是</Radio.Button>
                            <Radio.Button value={false}>否</Radio.Button>
                        </Radio.Group>
                    </Form.Item>

                    <Button onClick={onClose}>取消</Button>
                    <Button type="primary" htmlType="submit">
                        立即修改
                    </Button>

                </Form>
            </Drawer>

        </Qfpage>
    )
};

export default RoomList